package cn.xsly.ymcc.mq.listener;

import cn.xsly.ymcc.domain.PayFlow;
import cn.xsly.ymcc.domain.PayOrder;
import cn.xsly.ymcc.dto.PayResultVo;
import cn.xsly.ymcc.service.IPayOrderService;
import cn.xsly.ymcc.service.IPayService;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.util.Map;

public class PayOrderListener implements RocketMQLocalTransactionListener {
   @Autowired
   private IPayService payService;
   @Autowired
   private IPayOrderService payOrderService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        //保存本地的事物
        try {
            if(arg!=null && arg instanceof Map){
                Map<String,Object> map = (Map<String, Object>) arg;
                PayOrder payOrder = (PayOrder) map.get("payOrder");
                PayFlow payFlow = (PayFlow) map.get("payFlow");
                payService.updatePayOrderAndPayFlow(payOrder,payFlow);
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RocketMQLocalTransactionState.ROLLBACK;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        byte[] bytes =null;
        //msg
        if(msg == null || msg.getPayload() == null ){
            bytes =  (byte[]) msg.getPayload();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        try {
            //1.数据的转换
            String str = new String(bytes);
            PayResultVo payResultVo = JSON.parseObject(str, PayResultVo.class);
            //2.获取里面的订单号
            String orderNo = payResultVo.getOrderSn();

            //3.根据ordersn查询订单
            PayOrder payOrder = payOrderService.selectByOrderSn(orderNo);

            if (payOrder!=null&&payOrder.getPayStatus().equals(PayOrder.PAY_SUCCESS)){
                return RocketMQLocalTransactionState.COMMIT;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
